{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Multi-LLM Workflows\n",
    "\n",
    "This notebook demonstrates three simple multi-LLM workflows. They trade off cost or latency for potentially improved task performances:\n",
    "\n",
    "1. **Prompt-Chaining**: Decomposes a task into sequential subtasks, where each step builds on previous results\n",
    "2. **Parallelization**: Distributes independent subtasks across multiple LLMs for concurrent processing\n",
    "3. **Routing**: Dynamically selects specialized LLM paths based on input characteristics\n",
    "\n",
    "Note: These are sample implementations meant to demonstrate core concepts - not production code."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from concurrent.futures import ThreadPoolExecutor\n",
    "\n",
    "from util import extract_xml, llm_call"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def chain(input: str, prompts: list[str]) -> str:\n",
    "    \"\"\"Chain multiple LLM calls sequentially, passing results between steps.\"\"\"\n",
    "    result = input\n",
    "    for i, prompt in enumerate(prompts, 1):\n",
    "        print(f\"\\nStep {i}:\")\n",
    "        result = llm_call(f\"{prompt}\\nInput: {result}\")\n",
    "        print(result)\n",
    "    return result\n",
    "\n",
    "\n",
    "def parallel(prompt: str, inputs: list[str], n_workers: int = 3) -> list[str]:\n",
    "    \"\"\"Process multiple inputs concurrently with the same prompt.\"\"\"\n",
    "    with ThreadPoolExecutor(max_workers=n_workers) as executor:\n",
    "        futures = [executor.submit(llm_call, f\"{prompt}\\nInput: {x}\") for x in inputs]\n",
    "        return [f.result() for f in futures]\n",
    "\n",
    "\n",
    "def route(input: str, routes: dict[str, str]) -> str:\n",
    "    \"\"\"Route input to specialized prompt using content classification.\"\"\"\n",
    "    # First determine appropriate route using LLM with chain-of-thought\n",
    "    print(f\"\\nAvailable routes: {list(routes.keys())}\")\n",
    "    selector_prompt = f\"\"\"\n",
    "    Analyze the input and select the most appropriate support team from these options: {list(routes.keys())}\n",
    "    First explain your reasoning, then provide your selection in this XML format:\n",
    "\n",
    "    <reasoning>\n",
    "    Brief explanation of why this ticket should be routed to a specific team.\n",
    "    Consider key terms, user intent, and urgency level.\n",
    "    </reasoning>\n",
    "\n",
    "    <selection>\n",
    "    The chosen team name\n",
    "    </selection>\n",
    "\n",
    "    Input: {input}\"\"\".strip()\n",
    "\n",
    "    route_response = llm_call(selector_prompt)\n",
    "    reasoning = extract_xml(route_response, \"reasoning\")\n",
    "    route_key = extract_xml(route_response, \"selection\").strip().lower()\n",
    "\n",
    "    print(\"Routing Analysis:\")\n",
    "    print(reasoning)\n",
    "    print(f\"\\nSelected route: {route_key}\")\n",
    "\n",
    "    # Process input with selected specialized prompt\n",
    "    selected_prompt = routes[route_key]\n",
    "    return llm_call(f\"{selected_prompt}\\nInput: {input}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example Usage\n",
    "\n",
    "Below are practical examples demonstrating each workflow:\n",
    "1. Chain workflow for structured data extraction and formatting\n",
    "2. Parallelization workflow for stakeholder impact analysis\n",
    "3. Route workflow for customer support ticket handling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "Input text:\n",
      "\n",
      "Q3 Performance Summary:\n",
      "Our customer satisfaction score rose to 92 points this quarter.\n",
      "Revenue grew by 45% compared to last year.\n",
      "Market share is now at 23% in our primary market.\n",
      "Customer churn decreased to 5% from 8%.\n",
      "New user acquisition cost is $43 per user.\n",
      "Product adoption rate increased to 78%.\n",
      "Employee satisfaction is at 87 points.\n",
      "Operating margin improved to 34%.\n",
      "\n",
      "\n",
      "Step 1:\n",
      "92: customer satisfaction points\n",
      "45%: revenue growth\n",
      "23%: market share\n",
      "5%: customer churn\n",
      "8%: previous customer churn\n",
      "$43: user acquisition cost\n",
      "78%: product adoption rate\n",
      "87: employee satisfaction points\n",
      "34%: operating margin\n",
      "\n",
      "Step 2:\n",
      "92%: customer satisfaction\n",
      "45%: revenue growth\n",
      "23%: market share\n",
      "5%: customer churn\n",
      "8%: previous customer churn\n",
      "43.0: user acquisition cost\n",
      "78%: product adoption rate\n",
      "87%: employee satisfaction\n",
      "34%: operating margin\n",
      "\n",
      "Step 3:\n",
      "Here are the lines sorted in descending order by numerical value:\n",
      "\n",
      "92%: customer satisfaction\n",
      "87%: employee satisfaction\n",
      "78%: product adoption rate\n",
      "45%: revenue growth\n",
      "43.0: user acquisition cost\n",
      "34%: operating margin\n",
      "23%: market share\n",
      "8%: previous customer churn\n",
      "5%: customer churn\n",
      "\n",
      "Step 4:\n",
      "| Metric | Value |\n",
      "|:--|--:|\n",
      "| Customer Satisfaction | 92% |\n",
      "| Employee Satisfaction | 87% |\n",
      "| Product Adoption Rate | 78% |\n",
      "| Revenue Growth | 45% |\n",
      "| User Acquisition Cost | 43.0 |\n",
      "| Operating Margin | 34% |\n",
      "| Market Share | 23% |\n",
      "| Previous Customer Churn | 8% |\n",
      "| Customer Churn | 5% |\n"
     ]
    }
   ],
   "source": [
    "# Example 1: Chain workflow for structured data extraction and formatting\n",
    "# Each step progressively transforms raw text into a formatted table\n",
    "\n",
    "data_processing_steps = [\n",
    "    \"\"\"Extract only the numerical values and their associated metrics from the text.\n",
    "    Format each as 'value: metric' on a new line.\n",
    "    Example format:\n",
    "    92: customer satisfaction\n",
    "    45%: revenue growth\"\"\",\n",
    "    \"\"\"Convert all numerical values to percentages where possible.\n",
    "    If not a percentage or points, convert to decimal (e.g., 92 points -> 92%).\n",
    "    Keep one number per line.\n",
    "    Example format:\n",
    "    92%: customer satisfaction\n",
    "    45%: revenue growth\"\"\",\n",
    "    \"\"\"Sort all lines in descending order by numerical value.\n",
    "    Keep the format 'value: metric' on each line.\n",
    "    Example:\n",
    "    92%: customer satisfaction\n",
    "    87%: employee satisfaction\"\"\",\n",
    "    \"\"\"Format the sorted data as a markdown table with columns:\n",
    "    | Metric | Value |\n",
    "    |:--|--:|\n",
    "    | Customer Satisfaction | 92% |\"\"\",\n",
    "]\n",
    "\n",
    "report = \"\"\"\n",
    "Q3 Performance Summary:\n",
    "Our customer satisfaction score rose to 92 points this quarter.\n",
    "Revenue grew by 45% compared to last year.\n",
    "Market share is now at 23% in our primary market.\n",
    "Customer churn decreased to 5% from 8%.\n",
    "New user acquisition cost is $43 per user.\n",
    "Product adoption rate increased to 78%.\n",
    "Employee satisfaction is at 87 points.\n",
    "Operating margin improved to 34%.\n",
    "\"\"\"\n",
    "\n",
    "print(\"\\nInput text:\")\n",
    "print(report)\n",
    "formatted_result = chain(report, data_processing_steps)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MARKET IMPACT ANALYSIS FOR CUSTOMERS\n",
      "==================================\n",
      "\n",
      "HIGH PRIORITY IMPACTS\n",
      "-------------------\n",
      "1. Price Sensitivity\n",
      "- Rising inflation and costs likely to reduce purchasing power\n",
      "- Increased competition for value-oriented products\n",
      "- Risk of trading down to lower-cost alternatives\n",
      "\n",
      "Recommended Actions:\n",
      "• Introduce tiered pricing options\n",
      "• Develop value-focused product lines\n",
      "• Create loyalty programs with price benefits\n",
      "• Highlight total cost of ownership benefits\n",
      "\n",
      "2. Technology Demands\n",
      "- Accelerating tech advancement creating higher expectations\n",
      "- Integration of AI and smart features becoming standard\n",
      "- Mobile/digital-first experience requirements\n",
      "\n",
      "Recommended Actions:\n",
      "• Accelerate digital transformation initiatives\n",
      "• Invest in user experience improvements\n",
      "• Develop smart product features\n",
      "• Provide tech education and support\n",
      "\n",
      "MEDIUM PRIORITY IMPACTS\n",
      "----------------------\n",
      "3. Environmental Consciousness\n",
      "- Growing demand for sustainable products\n",
      "- Increased scrutiny of environmental practices\n",
      "- Willingness to pay premium for eco-friendly options\n",
      "\n",
      "Recommended Actions:\n",
      "• Develop eco-friendly product lines\n",
      "• Improve packaging sustainability\n",
      "• Communicate environmental initiatives\n",
      "• Create recycling programs\n",
      "\n",
      "MONITORING & METRICS\n",
      "-------------------\n",
      "• Track customer satisfaction scores\n",
      "• Monitor price sensitivity metrics\n",
      "• Measure adoption of new technologies\n",
      "• Track sustainability-related purchases\n",
      "• Regular customer feedback surveys\n",
      "\n",
      "RISK FACTORS\n",
      "------------\n",
      "• Economic downturn impact on spending\n",
      "• Tech adoption learning curve\n",
      "• Cost vs. sustainability trade-offs\n",
      "• Competition from specialized providers\n",
      "\n",
      "TIMELINE PRIORITIES\n",
      "------------------\n",
      "Immediate (0-3 months):\n",
      "- Price optimization\n",
      "- Digital experience improvements\n",
      "\n",
      "Short-term (3-12 months):\n",
      "- Tech feature development\n",
      "- Sustainability initiatives\n",
      "\n",
      "Long-term (12+ months):\n",
      "- Advanced technology integration\n",
      "- Comprehensive eco-friendly transformation\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
      "MARKET IMPACT ANALYSIS FOR EMPLOYEES\n",
      "\n",
      "Priority 1: Job Security Concerns\n",
      "Impacts:\n",
      "• Market volatility creating uncertainty about positions\n",
      "• Potential restructuring or role changes\n",
      "• Stress affecting productivity and morale\n",
      "\n",
      "Recommended Actions:\n",
      "- Provide regular, transparent communications about company stability\n",
      "- Create clear performance metrics tied to job security\n",
      "- Establish early warning systems for at-risk positions\n",
      "- Develop retention programs for key talent\n",
      "\n",
      "Priority 2: Skills Gap & Development\n",
      "Impacts:\n",
      "• Current skills becoming outdated due to market changes\n",
      "• New technologies/processes requiring additional training\n",
      "• Competitive disadvantage without upskilling\n",
      "\n",
      "Recommended Actions:\n",
      "- Conduct skills gap analysis\n",
      "- Implement targeted training programs\n",
      "- Provide learning stipends/resources\n",
      "- Create mentorship programs\n",
      "- Partner with educational institutions\n",
      "\n",
      "Priority 3: Strategic Direction & Leadership\n",
      "Impacts:\n",
      "• Uncertainty about career paths\n",
      "• Lack of alignment with company goals\n",
      "• Reduced engagement and commitment\n",
      "\n",
      "Recommended Actions:\n",
      "- Develop clear career progression frameworks\n",
      "- Create individual development plans\n",
      "- Increase leadership visibility and communication\n",
      "- Establish regular strategy updates and town halls\n",
      "- Implement feedback mechanisms\n",
      "\n",
      "Implementation Timeline:\n",
      "Short-term (0-3 months):\n",
      "• Begin transparent communications\n",
      "• Launch initial training assessments\n",
      "• Start regular strategy updates\n",
      "\n",
      "Medium-term (3-6 months):\n",
      "• Roll out training programs\n",
      "• Implement retention initiatives\n",
      "• Develop career frameworks\n",
      "\n",
      "Long-term (6+ months):\n",
      "• Monitor and adjust programs\n",
      "• Measure effectiveness\n",
      "• Refine strategic alignment\n",
      "\n",
      "Success Metrics:\n",
      "• Employee retention rates\n",
      "• Skills assessment scores\n",
      "• Employee satisfaction surveys\n",
      "• Productivity measures\n",
      "• Career progression rates\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
      "MARKET IMPACT ANALYSIS FOR INVESTORS\n",
      "\n",
      "Priority 1: Financial Performance\n",
      "Impacts:\n",
      "• Market volatility may affect expected returns\n",
      "• Economic uncertainty could slow growth targets\n",
      "• Cost inflation may squeeze margins\n",
      "\n",
      "Recommended Actions:\n",
      "- Implement enhanced financial reporting and forecasting\n",
      "- Develop contingency plans for different market scenarios\n",
      "- Identify cost optimization opportunities\n",
      "- Consider strategic M&A opportunities at lower valuations\n",
      "\n",
      "Priority 2: Risk Management\n",
      "Impacts:\n",
      "• Increased market risks require stronger controls\n",
      "• New regulatory requirements possible\n",
      "• Competitive landscape changes\n",
      "\n",
      "Recommended Actions:\n",
      "- Strengthen risk management frameworks\n",
      "- Increase frequency of risk assessments\n",
      "- Diversify investment portfolio\n",
      "- Maintain higher cash reserves\n",
      "\n",
      "Priority 3: Communication & Transparency\n",
      "Impacts:\n",
      "• Heightened investor scrutiny expected\n",
      "• Need for more detailed market analysis\n",
      "• Demand for regular updates\n",
      "\n",
      "Recommended Actions:\n",
      "- Enhance investor communications\n",
      "- Provide more frequent market updates\n",
      "- Share detailed mitigation strategies\n",
      "- Maintain open dialogue with key stakeholders\n",
      "\n",
      "Timeline Recommendations:\n",
      "Short-term (0-6 months):\n",
      "- Implement enhanced reporting\n",
      "- Review risk controls\n",
      "- Increase communication frequency\n",
      "\n",
      "Medium-term (6-18 months):\n",
      "- Execute cost optimization\n",
      "- Develop new growth strategies\n",
      "- Build strategic partnerships\n",
      "\n",
      "Long-term (18+ months):\n",
      "- Evaluate market position\n",
      "- Adjust investment strategy\n",
      "- Consider structural changes\n",
      "\n",
      "Key Success Metrics:\n",
      "• ROI performance\n",
      "• Cost reduction achievements\n",
      "• Risk incident rates\n",
      "• Investor satisfaction scores\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
      "MARKET IMPACT ANALYSIS FOR SUPPLIERS\n",
      "\n",
      "HIGH PRIORITY IMPACTS:\n",
      "1. Capacity Constraints\n",
      "- Reduced ability to meet customer demand\n",
      "- Risk of losing market share to competitors\n",
      "- Strain on existing infrastructure and resources\n",
      "- Potential breach of supply agreements\n",
      "\n",
      "Recommended Actions:\n",
      "• Invest in capacity expansion\n",
      "• Implement better demand forecasting\n",
      "• Develop contingency supplier network\n",
      "• Negotiate flexible delivery terms\n",
      "\n",
      "2. Price Pressures\n",
      "- Squeezed profit margins\n",
      "- Difficulty maintaining quality standards\n",
      "- Risk of losing customers to lower-cost alternatives\n",
      "- Cash flow challenges\n",
      "\n",
      "Recommended Actions:\n",
      "• Review cost structure and identify efficiencies\n",
      "• Negotiate long-term contracts with price adjustment clauses\n",
      "• Explore automation/process improvements\n",
      "• Consider strategic partnerships to share costs\n",
      "\n",
      "3. Technology Transitions\n",
      "- Need for new equipment and systems\n",
      "- Training requirements for workforce\n",
      "- R&D investment demands\n",
      "- Risk of obsolescence\n",
      "\n",
      "Recommended Actions:\n",
      "• Develop technology roadmap\n",
      "• Invest in workforce training\n",
      "• Seek innovation partnerships\n",
      "• Phase implementation of new technologies\n",
      "\n",
      "MEDIUM PRIORITY CONSIDERATIONS:\n",
      "- Supply chain resilience\n",
      "- Quality control processes\n",
      "- Market positioning\n",
      "- Customer relationship management\n",
      "\n",
      "LONG-TERM STRATEGIC RECOMMENDATIONS:\n",
      "1. Build financial reserves for future investments\n",
      "2. Develop diversification strategies\n",
      "3. Create innovation partnerships\n",
      "4. Strengthen customer relationships\n",
      "5. Invest in sustainability initiatives\n",
      "\n",
      "MONITORING METRICS:\n",
      "• Production capacity utilization\n",
      "• Price competitiveness\n",
      "• Technology adoption rates\n",
      "• Customer satisfaction levels\n",
      "• Market share trends\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
     ]
    }
   ],
   "source": [
    "# Example 2: Parallelization workflow for stakeholder impact analysis\n",
    "# Process impact analysis for multiple stakeholder groups concurrently\n",
    "\n",
    "stakeholders = [\n",
    "    \"\"\"Customers:\n",
    "    - Price sensitive\n",
    "    - Want better tech\n",
    "    - Environmental concerns\"\"\",\n",
    "    \"\"\"Employees:\n",
    "    - Job security worries\n",
    "    - Need new skills\n",
    "    - Want clear direction\"\"\",\n",
    "    \"\"\"Investors:\n",
    "    - Expect growth\n",
    "    - Want cost control\n",
    "    - Risk concerns\"\"\",\n",
    "    \"\"\"Suppliers:\n",
    "    - Capacity constraints\n",
    "    - Price pressures\n",
    "    - Tech transitions\"\"\",\n",
    "]\n",
    "\n",
    "impact_results = parallel(\n",
    "    \"\"\"Analyze how market changes will impact this stakeholder group.\n",
    "    Provide specific impacts and recommended actions.\n",
    "    Format with clear sections and priorities.\"\"\",\n",
    "    stakeholders,\n",
    ")\n",
    "\n",
    "for result in impact_results:\n",
    "    print(result)\n",
    "    print(\"+\" * 80)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Processing support tickets...\n",
      "\n",
      "\n",
      "Ticket 1:\n",
      "----------------------------------------\n",
      "Subject: Can't access my account\n",
      "    Message: Hi, I've been trying to log in for the past hour but keep getting an 'invalid password' error. \n",
      "    I'm sure I'm using the right password. Can you help me regain access? This is urgent as I need to \n",
      "    submit a report by end of day.\n",
      "    - John\n",
      "\n",
      "Response:\n",
      "----------------------------------------\n",
      "\n",
      "Available routes: ['billing', 'technical', 'account', 'product']\n",
      "Routing Analysis:\n",
      "\n",
      "This issue is clearly related to account access and authentication problems. The user is experiencing login difficulties with their password, which is a core account security and access issue. While there might be technical aspects involved, the primary concern is account access restoration. The urgency mentioned by the user and the nature of the problem (password/login issues) makes this a typical account support case. Account team specialists are best equipped to handle password resets, account verification, and access restoration procedures.\n",
      "\n",
      "\n",
      "Selected route: account\n",
      "Account Support Response:\n",
      "\n",
      "Dear John,\n",
      "\n",
      "I understand your urgency regarding account access. Before proceeding with account recovery, we must verify your identity to maintain security protocols.\n",
      "\n",
      "Immediate Steps for Account Recovery:\n",
      "1. Visit our secure password reset page at [secure portal URL]\n",
      "2. Click \"Forgot Password\"\n",
      "3. Enter your email address associated with the account\n",
      "4. Follow the verification instructions sent to your email\n",
      "\n",
      "Important Security Notes:\n",
      "• The reset link expires in 30 minutes\n",
      "• Do not share reset links or verification codes with anyone\n",
      "• Ensure you're on our official website (check for https:// and correct domain)\n",
      "\n",
      "WARNING: If you're unable to access your email or receive the reset link, additional verification will be required through our identity verification process.\n",
      "\n",
      "Additional Security Recommendations:\n",
      "- Enable Two-Factor Authentication after regaining access\n",
      "- Review recent account activity for unauthorized access\n",
      "- Update passwords on other accounts using similar credentials\n",
      "\n",
      "Expected Resolution Time:\n",
      "• Password reset: 5-10 minutes\n",
      "• Identity verification (if needed): 1-2 business hours\n",
      "\n",
      "If you continue experiencing issues, please respond with:\n",
      "1. Account email address\n",
      "2. Last successful login date\n",
      "3. Any recent account changes\n",
      "\n",
      "For urgent report submission, please contact your supervisor about deadline extension while we secure your account.\n",
      "\n",
      "Regards,\n",
      "Account Security Team\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
      "\n",
      "Ticket 2:\n",
      "----------------------------------------\n",
      "Subject: Unexpected charge on my card\n",
      "    Message: Hello, I just noticed a charge of $49.99 on my credit card from your company, but I thought\n",
      "    I was on the $29.99 plan. Can you explain this charge and adjust it if it's a mistake?\n",
      "    Thanks,\n",
      "    Sarah\n",
      "\n",
      "Response:\n",
      "----------------------------------------\n",
      "\n",
      "Available routes: ['billing', 'technical', 'account', 'product']\n",
      "Routing Analysis:\n",
      "\n",
      "This is clearly a billing-related inquiry as it involves:\n",
      "1. Questions about charges on a credit card\n",
      "2. Pricing plan discrepancy ($49.99 vs $29.99)\n",
      "3. Request for explanation of charges\n",
      "4. Potential request for refund/adjustment\n",
      "The customer is specifically questioning a financial transaction, which falls under the billing team's expertise. While it touches on account plans, the core issue is about charges and payment processing.\n",
      "\n",
      "\n",
      "Selected route: billing\n",
      "Billing Support Response:\n",
      "\n",
      "Dear Sarah,\n",
      "\n",
      "I understand your concern about the unexpected charge of $49.99 when you were expecting to be billed $29.99.\n",
      "\n",
      "After reviewing the charge, this difference typically occurs when:\n",
      "1. The promotional period for the $29.99 rate has ended\n",
      "2. There was a plan upgrade or change in service tier\n",
      "3. Additional services were added to the account\n",
      "\n",
      "To resolve this, I will:\n",
      "1. Review your account history within 1 business day\n",
      "2. Send you a detailed breakdown of the charges by email\n",
      "3. If an error is confirmed, process a refund within 2-3 business days\n",
      "4. Ensure your plan is set to the correct rate moving forward\n",
      "\n",
      "For immediate action, you can:\n",
      "- Review your current plan settings in your account dashboard\n",
      "- Send us your last billing statement for comparison\n",
      "- Provide any promotional codes you may have applied previously\n",
      "\n",
      "Payment options available:\n",
      "- If a refund is due, it will be credited to your original payment method\n",
      "- You can adjust your plan back to $29.99 through your account settings if eligible\n",
      "- Monthly auto-pay can be reviewed and updated as needed\n",
      "\n",
      "Please let me know if you need any additional information or have questions about these next steps.\n",
      "\n",
      "Best regards,\n",
      "Billing Support Team\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n",
      "\n",
      "Ticket 3:\n",
      "----------------------------------------\n",
      "Subject: How to export data?\n",
      "    Message: I need to export all my project data to Excel. I've looked through the docs but can't\n",
      "    figure out how to do a bulk export. Is this possible? If so, could you walk me through the steps?\n",
      "    Best regards,\n",
      "    Mike\n",
      "\n",
      "Response:\n",
      "----------------------------------------\n",
      "\n",
      "Available routes: ['billing', 'technical', 'account', 'product']\n",
      "Routing Analysis:\n",
      "\n",
      "This is clearly a technical/how-to question about product functionality. The user is asking for specific instructions about a feature (data export), and mentions looking through documentation. The question is about product usage and requires technical knowledge to explain the export process. Keywords like \"export,\" \"data,\" \"bulk export,\" and reference to documentation strongly indicate this is a technical support matter rather than billing, account, or general product inquiry.\n",
      "\n",
      "\n",
      "Selected route: technical\n",
      "Technical Support Response:\n",
      "\n",
      "I'll help you export your project data to Excel. Here's the complete process:\n",
      "\n",
      "Steps to Export Data:\n",
      "1. Log into your project dashboard\n",
      "2. Navigate to \"Project Settings\" in the top right corner\n",
      "3. Select \"Data Management\" from the dropdown menu\n",
      "4. Click the \"Export\" tab\n",
      "5. Choose \"Bulk Export\" option\n",
      "6. Select data range and specific fields to export\n",
      "7. Choose \"Excel (.xlsx)\" as the output format\n",
      "8. Click \"Generate Export\"\n",
      "9. Wait for the system to process (may take 1-15 minutes depending on data size)\n",
      "10. Download the exported file when ready\n",
      "\n",
      "System Requirements:\n",
      "- Supported browsers: Chrome 90+, Firefox 88+, Edge 91+\n",
      "- Minimum 2GB RAM available\n",
      "- Stable internet connection\n",
      "- Excel 2016 or later for opening exported files\n",
      "\n",
      "Common Issues & Workarounds:\n",
      "A. If export times out:\n",
      "   - Break data into smaller date ranges\n",
      "   - Export during off-peak hours\n",
      "   - Use filters to reduce data size\n",
      "\n",
      "B. If download fails:\n",
      "   - Clear browser cache\n",
      "   - Use incognito/private window\n",
      "   - Try a different supported browser\n",
      "\n",
      "Escalation Path:\n",
      "If you continue experiencing issues:\n",
      "1. Contact your project administrator\n",
      "2. Submit a ticket to technical support at support@company.com\n",
      "3. Include your project ID and any error messages received\n",
      "4. For urgent matters, call our support hotline: 1-800-XXX-XXXX\n",
      "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"
     ]
    }
   ],
   "source": [
    "# Example 3: Route workflow for customer support ticket handling\n",
    "# Route support tickets to appropriate teams based on content analysis\n",
    "\n",
    "support_routes = {\n",
    "    \"billing\": \"\"\"You are a billing support specialist. Follow these guidelines:\n",
    "    1. Always start with \"Billing Support Response:\"\n",
    "    2. First acknowledge the specific billing issue\n",
    "    3. Explain any charges or discrepancies clearly\n",
    "    4. List concrete next steps with timeline\n",
    "    5. End with payment options if relevant\n",
    "\n",
    "    Keep responses professional but friendly.\n",
    "\n",
    "    Input: \"\"\",\n",
    "    \"technical\": \"\"\"You are a technical support engineer. Follow these guidelines:\n",
    "    1. Always start with \"Technical Support Response:\"\n",
    "    2. List exact steps to resolve the issue\n",
    "    3. Include system requirements if relevant\n",
    "    4. Provide workarounds for common problems\n",
    "    5. End with escalation path if needed\n",
    "\n",
    "    Use clear, numbered steps and technical details.\n",
    "\n",
    "    Input: \"\"\",\n",
    "    \"account\": \"\"\"You are an account security specialist. Follow these guidelines:\n",
    "    1. Always start with \"Account Support Response:\"\n",
    "    2. Prioritize account security and verification\n",
    "    3. Provide clear steps for account recovery/changes\n",
    "    4. Include security tips and warnings\n",
    "    5. Set clear expectations for resolution time\n",
    "\n",
    "    Maintain a serious, security-focused tone.\n",
    "\n",
    "    Input: \"\"\",\n",
    "    \"product\": \"\"\"You are a product specialist. Follow these guidelines:\n",
    "    1. Always start with \"Product Support Response:\"\n",
    "    2. Focus on feature education and best practices\n",
    "    3. Include specific examples of usage\n",
    "    4. Link to relevant documentation sections\n",
    "    5. Suggest related features that might help\n",
    "\n",
    "    Be educational and encouraging in tone.\n",
    "\n",
    "    Input: \"\"\",\n",
    "}\n",
    "\n",
    "# Test with different support tickets\n",
    "tickets = [\n",
    "    \"\"\"Subject: Can't access my account\n",
    "    Message: Hi, I've been trying to log in for the past hour but keep getting an 'invalid password' error.\n",
    "    I'm sure I'm using the right password. Can you help me regain access? This is urgent as I need to\n",
    "    submit a report by end of day.\n",
    "    - John\"\"\",\n",
    "    \"\"\"Subject: Unexpected charge on my card\n",
    "    Message: Hello, I just noticed a charge of $49.99 on my credit card from your company, but I thought\n",
    "    I was on the $29.99 plan. Can you explain this charge and adjust it if it's a mistake?\n",
    "    Thanks,\n",
    "    Sarah\"\"\",\n",
    "    \"\"\"Subject: How to export data?\n",
    "    Message: I need to export all my project data to Excel. I've looked through the docs but can't\n",
    "    figure out how to do a bulk export. Is this possible? If so, could you walk me through the steps?\n",
    "    Best regards,\n",
    "    Mike\"\"\",\n",
    "]\n",
    "\n",
    "print(\"Processing support tickets...\\n\")\n",
    "for i, ticket in enumerate(tickets, 1):\n",
    "    print(f\"\\nTicket {i}:\")\n",
    "    print(\"-\" * 40)\n",
    "    print(ticket)\n",
    "    print(\"\\nResponse:\")\n",
    "    print(\"-\" * 40)\n",
    "    response = route(ticket, support_routes)\n",
    "    print(response)\n",
    "    print(\"+\" * 80)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ultralytics",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
